import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.neo4j.driver.*;
import org.neo4j.driver.Record;

import static org.neo4j.driver.Values.parameters;

public class CrudTest {
    private Driver driver;
    @Before
    public void init(){
        String url="bolt://192.168.1.21:7687";
        String username="neo4j";
        String password="neo4jneo4j";
        this.driver=GraphDatabase.driver(url, AuthTokens.basic(username,password));
    }

    @After
    public void close(){
        this.driver.close();
    }

    /**
     * 新增数据
     */
    @Test
    public void testCreate(){
        try(Session session=this.driver.session()){
            session.executeWrite(tx->{
                String cypher="create (n:User {name:$name1}) -[r:BEOTHER_OF]->(m:User {name:$name2}) return n,r,m";
                Result result = tx.run(cypher, parameters("name1", "刘备", "name2", "关羽"));
                while (result.hasNext()){
                    Record record = result.next();
                    System.out.println(record.get("n").get("name"));
                    System.out.println(record.get("m").get("name"));
                }
                return "ok";
            });
        }
    }

    /**
     * 更新数据
     */
    @Test
    public void testUpdate() {
        try(Session session=this.driver.session()){
            session.executeWrite(tx->{
               String cypher="match (n:User {name:$name}) set n.age=$age return n.age as age";
                Result result = tx.run(cypher, parameters("name", "刘备", "age", 30));
                while (result.hasNext()){
                    Record record = result.next();
                    System.out.println(record.get("age"));
                }
                return "ok";
            });
        }
    }

    /**
     * 查询数据
     */
    @Test
    public void testQuery() {
        try(Session session=this.driver.session()){
            session.executeRead(tx->{
                String cypher="match (n:User {name:$name}) return n";
                Result result = tx.run(cypher, parameters("name", "刘备"));
                while (result.hasNext()){
                    Record record = result.next();
                    System.out.println(record.get("n").get("name"));
                    System.out.println(record.get("n").get("age"));
                }
                return "ok";
            });
        }
    }

    /**
     * 删除数据
     */
    @Test
    public void testDelete() {
        try(Session session=this.driver.session()){
            Integer count = session.executeWrite(tx -> {
                String cypher = "match (n:User {name:$name}) -[r]->(m) detach delete n,m,r return count(*) as count";
                Result result = tx.run(cypher, parameters("name", "刘备"));
                return result.single().get("count").asInt();
            });
            System.out.println(count);
        }
    }


}
